package com.bailiban.spit.service;

import com.bailiban.common.util.IdWorker;
import com.bailiban.spit.dao.SpitDao;
import com.bailiban.spit.entity.Spit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * @author zhulang
 * @Classname SpitService
 * @Description SpitService
 */
@Service
public class SpitService {
    @Autowired
    private SpitDao spitDao;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 查询所有spit
     *
     * @return
     */
    public List<Spit> findAll() {
        return spitDao.findAll();
    }

    /**
     * 根据id查询spit
     *
     * @param id
     * @return
     */
    public Spit findById(String id) {
        return spitDao.findById(id).get();

    }

    /**
     * 新增
     *
     * @param spit
     */
    public void insert(Spit spit) {
        spit.set_id(idWorker.nextId() + "");
        spit.setPublishtime(new Date());
        spit.setShare(0);
        spit.setState("1");
        spit.setThumbup(1);
        spit.setVisits(1);
        if (!StringUtils.isEmpty(spit.getParentid())) {
//            父id存在表示发布的是评论
            Query query = new Query();
            query.addCriteria(Criteria.where("_id").is(spit.getParentid()));
            Update update = new Update();
            update.inc("comment", 1);
            mongoTemplate.updateFirst(query, update, Spit.class);
        }
//        否则表示发布的是吐槽
        spitDao.insert(spit);
    }

    public void update(Spit spit) {
        spitDao.save(spit);
    }

    public void deleteByid(String id) {
        spitDao.deleteById(id);
    }

    public Page findByParentId(String parentid, int page, int size) {
        PageRequest pageRequest = PageRequest.of(page - 1, size);
        return spitDao.findByParentid(parentid, pageRequest);
    }

    public void thumbup(String id) {
       /* Spit spit = spitDao.findById(id).get();
        spit.setThumbup(spit.getThumbup() + 1);
        spitDao.save(spit);*/

        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(id));
        Update update = new Update();
        update.inc("thumbup", 1);
        mongoTemplate.updateFirst(query, update, Spit.class);
    }
}
